var express = require('express');
var router = express();
const db = require("../../common/mysql");
const user = require("../../model/user")

const { addUserInfo } = user
// 添加用户
router.post('/add', async function (req, res, next) {
  const { name, sex, remark } = req.query
  const data = await addUserInfo({ name, sex, remark })
  res.send({
    code: 200,
    msg: 'success',
    obj: data
  })
});

// 查询分页用户
router.get('/list', function (req, res, next) {
  db.query('select id,name,sex,remark from user where display!=0', (err, rows) => {
    if (!err) {
      res.send({
        code: 200,
        msg: 'success',
        obj: rows
      })
    } else {
      res.send({
        code: 201,
        msg: 'error'
      })
    }
  })
});

// 根据id删除用户
router.delete('/delById', function (req, res, next) {
  const { ids } = req.query
  console.log(req.query)
  console.log('SQL: ', `update user set display=0 where id in (${ids})`)
  db.query(`update user set display=0 where id in ('${ids}')`, (err, rows) => {
    if (!err) {
      res.send({
        code: 200,
        msg: 'success',
        obj: `成功删除${rows.affectedRows}条记录`
      })
    } else {
      res.send({
        code: 201,
        msg: 'error'
      })
    }
  })
});

// 根据id查询用户
router.get('/ById', function (req, res) {
  const { id } = req.query
  db.query(`select id,name,sex,remark from user where id=${id} and display!=0`, (err, rows) => {
    if (!err) {
      res.send({
        code: 200,
        msg: 'success',
        obj: rows
      })
    } else {
      res.send({
        code: 201,
        msg: 'error'
      })
    }
  })
});

module.exports = router;
